package com.p7.notepad.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.admix.AdmixData;
import com.admix.AdmixEdit;
import com.google.gson.Gson;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.p7.notepad.R;
import com.p7.notepad.adapter.SpinnerAdapter;
import com.p7.notepad.app.BaseActivity;
import com.p7.notepad.bean.File;
import com.p7.notepad.bean.Success;
import com.p7.notepad.network.APIManager;
import com.p7.notepad.network.exception.ExceptionHandle;
import com.p7.notepad.network.listener.RequestListener;
import com.p7.notepad.tools.FileUtils;
import com.p7.notepad.tools.ImageUtils;
import com.p7.notepad.tools.PhotoUtils;
import com.p7.notepad.tools.Storage;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class AddNotepadActivity extends BaseActivity implements AdapterView.OnItemSelectedListener {

    @BindView(R.id.add_notepad_file_name)
    TextView mFileName;
    @BindView(R.id.add_notepad_title)
    EditText mTitle;
    @BindView(R.id.add_notepad_rich)
    AdmixEdit mRich;
    @BindView(R.id.add_notepad_btn)
    LinearLayout mBtns;
    @BindView(R.id.add_notepad_file_spinner)
    Spinner mFileSpinner;

    private SpinnerAdapter mAdapter;

    private PhotoUtils photoUtils;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_notepad;
    }

    @Override
    protected void onResume() {
        super.onResume();
        getFile();
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        mAdapter = new SpinnerAdapter();
        mFileSpinner.setAdapter(mAdapter);
        mFileSpinner.setOnItemSelectedListener(this);

        photoUtils = new PhotoUtils();
        photoUtils.setWith(this).setListener(new PhotoUtils.OnPhotoListener() {
            @Override
            public void onPhotoStart() {
            }
            @Override
            public void onPhotoPath(String imagePath) {
                APIManager.uploadFile("file/uploadFile", imagePath, new RequestListener() {
                    @Override
                    public void onSuccess(String s) {
                        Gson gson = new Gson();
                        Success success = gson.fromJson(s, Success.class);
                        if (success.getCode() == 1000) {
                            mRich.setImage(String.valueOf(success.getData()));
                        } else if(success.getCode() == 2001) {
                            startActivity(LoginActivity.class);
                        } else {
                            setToast(success.getMessage());
                        }
                    }
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable error) {
                        setToast(error.message);
                    }
                }, null);

            }
            @Override
            public void onPhotoError(String error) {
                setToast(error);
            }
        });
    }

    @OnClick({R.id.add_notepad_quit, R.id.add_notepad_preserve, R.id.add_notepad_voice, R.id.add_notepad_image,
            R.id.add_notepad_phone, R.id.add_notepad_album, R.id.add_notepad_cancel, R.id.add_notepad_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_notepad_quit:
                finish();
                break;
            case R.id.add_notepad_preserve: // 保存
                submit();
                break;
            case R.id.add_notepad_file_refresh:
                getFile();
                break;
            case R.id.add_notepad_voice: //
                btnVoice();
                break;
            case R.id.add_notepad_image:
                mBtns.setVisibility(View.VISIBLE);
                break;
            case R.id.add_notepad_phone:
                photoUtils.onCamera();
                mBtns.setVisibility(View.GONE);
                break;
            case R.id.add_notepad_album:
                photoUtils.onPhoto();
                mBtns.setVisibility(View.GONE);
                break;
            case R.id.add_notepad_cancel:
                mBtns.setVisibility(View.GONE);
                break;
            case R.id.add_notepad_btn:
                mBtns.setVisibility(View.GONE);
                break;
        }
    }

    private String getInfo() {
        for (AdmixData data : mRich.getDatas()) {
            if (TextUtils.isEmpty(data.getUrl()) && TextUtils.isEmpty(data.getInput())) {
                mRich.getDatas().remove(data);
            }
        }
        return new Gson().toJson(mRich.getDatas());
    }

    //TODO 开始说话：
    private void btnVoice() {
        RecognizerDialog dialog = new RecognizerDialog(this, null);
        dialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        dialog.setParameter(SpeechConstant.ACCENT, "mandarin");

        dialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                printResult(recognizerResult);
            }

            @Override
            public void onError(SpeechError speechError) {
            }
        });
        dialog.show();
//        Toast.makeText(this, "请开始说话", Toast.LENGTH_SHORT).show();
    }

    //回调结果：
    private void printResult(RecognizerResult results) {
        String text = parseIatResult(results.getResultString());
        // 自动填写地址
        if (TextUtils.isEmpty(mTitle.getText().toString())) {
            mTitle.append(text);
        } else {
            mRich.append(text);
        }

    }

    public static String parseIatResult(String json) {
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);
            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词，默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret.toString();
    }

    private void submit() {
        if (data == null) {
            setToast("您还未选则文件夹");
            return;
        }
        String info = getInfo();
        if (TextUtils.isEmpty(info)) {
            setToast("您还未输入内容");
            return;
        }
        Map<String, String> parameters = new HashMap<>();
        parameters.put("userId", String.valueOf(Storage.getId()));
        parameters.put("title", mTitle.getText().toString());
        parameters.put("info", info);
        parameters.put("folderId", String.valueOf(data.getId()));
        APIManager.onPost("notepad/newNotepad", parameters, new RequestListener() {
            @Override
            public void onSuccess(String s) {
                Gson gson = new Gson();
                Success success = gson.fromJson(s, Success.class);
                if (success.getCode() == 1000) {
                    setToast("记事本新建成功");
                    finish();
                } else if (success.getCode() == 2001) {
                    startActivity(LoginActivity.class);
                    finish();
                } else {
                    setToast("记事本新建失败，请稍后重试");
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable error) {
                setToast("记事本新建失败，请稍后重试");
            }
        });

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        data = mAdapter.getDatas().get(position);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    private File.DataBean data; // 默认选中文件夹

    private void getFile() {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("userId", String.valueOf(Storage.getId()));
        parameters.put("pageNum", String.valueOf(1));
        parameters.put("pageSize", String.valueOf(100));
        APIManager.onPost("folder/getFolder", parameters, new RequestListener() {
            @Override
            public void onSuccess(String s) {
                Gson gson = new Gson();
                File file = gson.fromJson(s, File.class);
                if (file.getCode() == 1000) {
                    if (file.getData() != null && file.getData().size() > 0) {
                        data = file.getData().get(0);
                        mAdapter.onRefresh(file.getData());
                    } else {
                        startActivity(AddFileActivity.class);
                        setToast("您还没有文件夹，请先新建");
                    }
                } else if (file.getCode() == 2001) {
                    startActivity(LoginActivity.class);
                    finish();
                } else {
                    setToast("文件夹获取失败，请稍后重试");
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable error) {
                setToast("文件夹获取失败，请稍后重试");
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        photoUtils.onActivityResult(this, requestCode, resultCode, data);
    }

    private void setToast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

}
